package com.aabte.permissionframeworklearn.permission.service;

import com.aabte.permissionframeworklearn.permission.common.RequestHolder;
import com.aabte.permissionframeworklearn.permission.mapper.SysUserMapper;
import com.aabte.permissionframeworklearn.permission.mapper.SysUserRoleMapper;
import com.aabte.permissionframeworklearn.permission.model.SysUser;
import com.aabte.permissionframeworklearn.permission.model.SysUserRole;
import com.aabte.permissionframeworklearn.permission.util.IpUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author Daniel
 */
@Service
public class SysRoleUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysLogService sysLogService;

    public List<SysUser> getUsersByRoleId(Long roleId) {

        List<Long> userIdList = sysUserRoleMapper.getUserIdListByRoleId(roleId);
        if (CollectionUtils.isEmpty(userIdList)) {
            return Lists.newArrayList();
        }

        List<SysUser> sysUsers = sysUserMapper.getByIdList(userIdList);
        return sysUsers;
    }

    public void changeUser(Long roleId, List<Long> userIds) {
        // 获取角色当前关联的用户ID
        List<Long> originUserIdList = sysUserRoleMapper.getUserIdListByRoleId(roleId);

        // 是否有更新
        if (userIds.size() == originUserIdList.size()) {
            Set<Long> userIdSet = Sets.newHashSet(originUserIdList);
            userIdSet.addAll(userIds);
            if (userIdSet.size() == userIds.size()) {
                return;
            }
        }
        updateRoleUser(roleId, userIds);
        sysLogService.saveRoleUserLog(roleId, originUserIdList, userIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateRoleUser(Long roleId, List<Long> userIds) {
        // 删除当前所有关联的用户ID
        sysUserRoleMapper.deleteByRoleId(roleId);

        if (CollectionUtils.isEmpty(userIds)) {
            return;
        }

        // 重新关联用户ID
        List<SysUserRole> sysUserRoles = Lists.newArrayList();
        for (Long userId : userIds) {
            SysUserRole sysUserRole = SysUserRole.builder()
                    .roleId(roleId)
                    .userId(userId)
                    .operateTime(new Date())
                    .operator(RequestHolder.getCurrentUser().getUsername())
                    .operateIp(IpUtil.getRemoteIpAddress(RequestHolder.getCurrentRequest()))
                    .build();
            sysUserRoles.add(sysUserRole);
        }

        sysUserRoleMapper.batchInsert(sysUserRoles);
    }
}
